import {
	reactive,
	ref,
	toRefs,
	getCurrentInstance,
	watch,
	computed
} from "vue"
import {
	onReady,
	onLoad,
	onShow,
	onReachBottom,
	onPullDownRefresh
} from '@dcloudio/uni-app'

import store from '@/store/index.js'; //需要引入store

export default function() {
	const {
		proxy
	} = getCurrentInstance()

	const total = ref(0)
	// const page = ref(1)
	const current_page = ref(1)
	const page_size = ref(20)
	const last_page = ref(1)
	const apiPath = ref('')
	const ascended = ref(false) //排序方式
	const sortFieldName = ref('created') //排序属性名
	const loading = ref(false)
	const list = reactive([])
	const searchParams = reactive({})
	const loadmoreStatus = ref('loading')
	watch(loading, async (val) => {
		if (val) {
			loadmoreStatus.value = 'loading'
		} else {
			if (list.length == 0) {
				loadmoreStatus.value = 'nodata'
			} else if (current_page.value < last_page.page) {
				loadmoreStatus.value = 'loadmore'
			} else {
				loadmoreStatus.value = 'nomore'
			}
		}
	})

	const searchConfirm = async () => {
		await getList(1)
	}
	const searchClear = async (fileds) => {
		console.log('searchClear');
		fileds.forEach(v => {
			searchParams[v] = ''
		})
		await getList(1)
	}

	function delay(ms) {
		return new Promise(resolve => setTimeout(resolve, ms));
	}

	const getList = async (page) => {
		!page && (page = 1);
		if (!apiPath.value) {
			return;
		}
		if (page == 1) {
			list.splice(0, list.length);
		}
		let params = {
			current: page,
			size: page_size.value,
			ascended: ascended.value,
			sortFieldName: sortFieldName.value,
			...searchParams
		}
		for (let key in params) {
			if ((params[key] + '').trim() === '') {
				delete params[key]
			}
		}
		loading.value = true
		await proxy.$u.api[apiPath.value](params).then(res => {
			let {
				data,
				code,
				msg
			} = res;
			if (code == 200) {
				current_page.value = Number(data.current);
				total.value = Number(data.total);
				last_page.value = Math.round(total.value/page_size.value)+1;
				data.records.forEach((v, i) => {
					list.push(v)
				})
				// uni.hideLoading()
			} else {
				uni.$u.toast(msg || '错误');
			}
			loading.value = false
			uni.stopPullDownRefresh()
		}).catch(res => {
			loading.value = false
			uni.stopPullDownRefresh()
		})
	}

	onReachBottom(() => {
		console.log('onReachBottom');
		if (loading.value) {
			return;
		}
		if (current_page < last_page) {
			getList(current_page.value + 1)
		}
	})
	onPullDownRefresh(async () => {
		await getList(1)
	})
	// // 切换每页显示条数
	// watch(pageSize, async (val) => {
	//     page.value = 1
	//     await getData()
	// })

	return {
		total,
		// page,
		current_page,
		page_size,
		last_page,
		ascended,
		sortFieldName,
		apiPath,
		loading,
		list,
		searchParams,
		getList,
		loadmoreStatus,
		searchClear,
		searchConfirm
	}
}